<script setup lang="ts">
import AnalyesAPI from "@/api/system/analyes";
import { useAnalysetStore } from "@/store";
import { ref } from "vue";
import router from "@/router";
import { getUserInfo } from "@/utils/auth";
import dayjs from "dayjs";
import LectureAPI from "@/api/system/lecture";

const {
  waterForm,
  handleAddWaterPh,
  getWaterCapacity,
  switchAdd,
  downloadDetail,
} = defineProps<{
  handleAddWaterPh: (message: string) => void;
  getWaterCapacity: (message: string) => void;
  handleSwitch: (message: string) => void;
  downloadDetail: (message: string) => void;
  waterForm: Object;
  switchAdd: Boolean;
  switchAB: Boolean;
  switch: Boolean;
}>();

const analyseStatusPage = useAnalysetStore();
const drawer2 = ref(false);
const sampleSnList = ref([]);
const userInfo = JSON.parse(getUserInfo()); //当前用户信息
const checkDialogVisible = ref(false); //提交校核日期
const issuedDialogVisible = ref(false); // 控制校核弹框
const auditList = ref([]); // 审核人数组
const auditDialogVisible = ref(false); // 选择审核人的弹框
const issuedUserId = ref(""); // 选择审核人样式
const issuedUserName = ref(""); // 选择审核人样式
const isauditDialogVisible = ref(false); // 审核的弹框
let checkTime = ref("");

// 校核
const issuedForm = ref({
  add_form_id: analyseStatusPage.waterForm.add_form_id,
  check_content: "",
  result: "",
});
// 审核
const isauditForm = ref({
  add_form_id: analyseStatusPage.waterForm.add_form_id,
  review_content: "",
  result: "",
});

// 样品编号
const handleSwitchdrawer = () => {
  let json = {
    task_id: analyseStatusPage.waterForm.taskId,
    // sampling_date: waterForm.value.sampling_time,
    category_id: analyseStatusPage.waterForm.tableItem.sample_category_id,
    test_parms: analyseStatusPage.waterForm.tableItem.test_parms,
    test_category: analyseStatusPage.waterForm.test_category,
  };
  AnalyesAPI.getSamplesn(json).then((res) => {
    drawer2.value = true;
    sampleSnList.value = res;
  });
};

// 取消按钮
const handlePageList = () => {
  router.push({ path: "/analyse/sample-analysis" });
};

// 控制保存的按钮
const saveShowButton = computed(() => {
  let editPersonnelList = analyseStatusPage.waterForm.tableItem.analysis_uids
    .split(",")
    .map(Number);
  const checkStatus =
    waterForm.check_status !== undefined
      ? waterForm.check_status
      : analyseStatusPage.waterForm.tableItemList.check_statuses;
  return (
    editPersonnelList.includes(userInfo.id) &&
    (checkStatus === 0 || checkStatus === 2 || checkStatus === 5)
  );
});

// 控制校核的按钮
const shouldShowButton = computed(() => {
  return (
    analyseStatusPage.waterForm.tableItem.check_uid === userInfo.id &&
    waterForm.check_status === 1
  );
});

// 控制提交审核的按钮
const submitShowButton = computed(() => {
  return (
    analyseStatusPage.waterForm.tableItem.check_uid === userInfo.id &&
    waterForm.check_status === 3
  );
});

// 控制审核的按钮
const auditShowButton = computed(() => {
  return waterForm.reviewer_id == userInfo.id && waterForm.check_status === 4;
});

// 打开校核弹框
const getUpdatedData = () => {
  checkDialogVisible.value = true;
};
const handleCheckClose = () => {
  checkDialogVisible.value = false;
};

// 打开校核弹框
const openSubmitAuditClose = () => {
  issuedDialogVisible.value = true;
};

// 关闭校核弹框
const handleSubmitAuditClose = () => {
  issuedDialogVisible.value = false;
};

// 确认提交校核
const handleSubmit = () => {
  if (switchAdd) {
    // 调用保存接口
    handleAddWaterPh();
  }
  const formattedDate = checkTime.value
    ? dayjs(checkTime.value).format("YYYY-MM-DD")
    : "";
  console.log(analyseStatusPage.waterForm.id);
  AnalyesAPI.handleCheckTimeData({
    id: analyseStatusPage.waterForm.add_form_id,
    submit_date: formattedDate,
  }).then((data) => {
    ElMessage.success("提交成功！");
    checkDialogVisible.value = false;
    // 获取表单信息
    getWaterCapacity();
  });
};

// 校核结果
const handleIssuedSubmit = () => {
  AnalyesAPI.handleCheckRecord(issuedForm.value).then((data) => {
    ElMessage.success("提交成功");
    issuedDialogVisible.value = false;
    // 获取表单信息状态
    getWaterCapacity();
  });
};

// 打开选择审核人弹框
const openAuditClose = () => {
  LectureAPI.getCheckStaff({ group: "22" }).then((data) => {
    auditList.value = data.filter((user) => user.id !== userInfo.id);
    console.log("审核人", auditList.value);
    auditDialogVisible.value = true;
  });
};

// 关闭选择审核人弹框
const handleAuditClose = () => {
  auditDialogVisible.value = false;
};

// 选择审核人
const toggleIssuedSelection = (id, name) => {
  issuedUserId.value = id;
  issuedUserName.value = name;
};

// 提交审核人
const handleSubmitAudit = () => {
  let json = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    user_ids: issuedUserId.value,
    usernames: issuedUserName.value,
  };
  AnalyesAPI.handleAddReviewer(json).then((res) => {
    console.log(res);
    if (res == 1) {
      ElMessage.success("提交成功！");
      auditDialogVisible.value = false;
      // 获取表单信息状态
      getWaterCapacity();
    }
  });
};

// 关闭审核弹框
const openAuditOutcomeClose = () => {
  isauditDialogVisible.value = true;
};

// 关闭审核弹框
const handleAuditOutcomeClose = () => {
  isauditDialogVisible.value = false;
};

// 确认审核结果
const handleAuditOutcomeSubmit = () => {
  AnalyesAPI.handleReviewRecord(isauditForm.value).then((res) => {
    console.log(res);
    ElMessage.success("审核成功");
    isauditDialogVisible.value = false;
    // 获取表单信息状态
    getWaterCapacity();
  });
};
</script>

<template>
  <div>
    <el-card class="box-card" style="margin-top: 30px">
      <div style="display: flex; justify-content: space-between">
        <!--        占位盒子-->
        <div>
          <!--          <el-button @click="handleSwitchdrawer">-->
          <!--            样品编号-->
          <!--          </el-button>-->
          <el-button v-show="switch" @click="handleSwitch">
            {{ switchAB ? "B面" : "A面" }}
          </el-button>
        </div>
        <div>
          <el-button @click="handlePageList">取消</el-button>
          <!--          <el-button>新增</el-button>-->
          <!--          <el-button>复制并新增</el-button>-->
          <el-button v-show="saveShowButton" @click="handleAddWaterPh">
            保存
          </el-button>
          <el-button
            v-show="saveShowButton"
            type="primary"
            @click="getUpdatedData"
          >
            提交
          </el-button>
          <el-button
            v-show="shouldShowButton"
            type="primary"
            @click="openSubmitAuditClose"
          >
            校核
          </el-button>
          <el-button
            v-show="submitShowButton"
            type="primary"
            @click="openAuditClose"
          >
            提交
          </el-button>
          <el-button
            v-show="auditShowButton"
            type="primary"
            @click="openAuditOutcomeClose"
          >
            审核
          </el-button>
          <!--          &lt;!&ndash;          <el-button type="primary" @click="openIssuedPersonClose">提交签发人</el-button>&ndash;&gt;-->
          <!--          &lt;!&ndash;          <el-button type="primary" @click="openSuedPersonClose">签发</el-button>&ndash;&gt;-->
          <el-button type="primary" @click="downloadDetail">下载</el-button>
        </div>
      </div>
    </el-card>
    <!--    样品编号-->
    <el-drawer v-model="drawer2" direction="rtl">
      <template #header>
        <h2 style="color: #000">相关采样样品编号</h2>
      </template>
      <el-table border style="width: 100%" :data="sampleSnList">
        <el-table-column label="序号">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="sample_sn" label="样品编号" />
        <el-table-column prop="sampling_date" label="采样时间" />
      </el-table>
    </el-drawer>
    <!--    校核日期-->
    <el-dialog
      v-model="checkDialogVisible"
      title="提交校核"
      width="30%"
      center
      :before-close="handleCheckClose"
    >
      <div class="check">
        <!--        头部-->
        <div
          class="check-header"
          style="display: flex; align-items: center; margin-bottom: 20px"
        >
          <p>表单填写日期：</p>
          <el-date-picker
            v-model="checkTime"
            style="border: 1px solid #cccccc; border-radius: 6px; width: 70%"
            type="date"
            placeholder="请选择"
          />
        </div>
        <div class="check-footer">
          <el-button style="width: 48%" @click="handleCheckClose">
            取消
          </el-button>
          <el-button type="primary" style="width: 48%" @click="handleSubmit">
            确认
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!--    提交校核-->
    <el-dialog
      v-model="issuedDialogVisible"
      title="提交校核"
      :before-close="handleSubmitAuditClose"
      :show-close="false"
      width="30%"
      center
    >
      <div class="check">
        <!--        头部-->
        <div class="check-center">
          <div style="display: flex; align-items: center; margin-bottom: 10px">
            校核结果：
            <el-radio-group v-model="issuedForm.result">
              <el-radio value="1" size="large">同意</el-radio>
              <el-radio value="0" size="large">拒绝</el-radio>
            </el-radio-group>
          </div>
          <div
            v-show="issuedForm.result === '0'"
            style="margin-top: 20px; width: 100%"
          >
            <el-form>
              <el-form-item label="拒绝原因：">
                <el-input
                  v-model="issuedForm.check_content"
                  :rows="2"
                  type="textarea"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="check-footer">
          <el-button style="width: 48%" @click="handleSubmitAuditClose">
            取消
          </el-button>
          <el-button
            type="primary"
            style="width: 48%"
            @click="handleIssuedSubmit"
          >
            确认
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!--    选择审核人-->
    <el-dialog
      v-model="auditDialogVisible"
      title="选择审核人"
      :before-close="handleAuditClose"
      :show-close="false"
      width="30%"
      center
    >
      <div class="check">
        <!--        头部-->
        <div class="check-center">
          <div
            v-for="(item, index) in auditList"
            :key="index"
            class="check-center-item"
            :class="{ 'check-active': item.id === issuedUserId }"
            @click="toggleIssuedSelection(item.id, item.username)"
          >
            {{ item.username }}
            <div v-if="item.id === issuedUserId" class="check-icon">
              <svg-icon icon-class="confirm" size="16" />
            </div>
          </div>
        </div>
        <div class="check-footer">
          <el-button style="width: 48%" @click="handleAuditClose">
            取消
          </el-button>
          <el-button
            type="primary"
            style="width: 48%"
            @click="handleSubmitAudit"
          >
            确认
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!--    审核结果-->
    <el-dialog
      v-model="isauditDialogVisible"
      title="提交审核"
      :before-close="handleAuditOutcomeClose"
      :show-close="false"
      width="30%"
      center
    >
      <div class="check">
        <!--        头部-->
        <div class="check-center">
          <div style="display: flex; align-items: center; margin-bottom: 20px">
            审核结果：
            <el-radio-group v-model="isauditForm.result">
              <el-radio value="1" size="large">同意</el-radio>
              <el-radio value="0" size="large">拒绝</el-radio>
            </el-radio-group>
          </div>
          <div v-show="isauditForm.result === '0'" style="margin-top: 20px">
            <el-form>
              <el-form-item label="拒绝原因：">
                <el-input
                  v-model="isauditForm.review_content"
                  :rows="2"
                  type="textarea"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="check-footer">
          <el-button style="width: 48%" @click="handleAuditOutcomeClose">
            取消
          </el-button>
          <el-button
            type="primary"
            style="width: 48%"
            @click="handleAuditOutcomeSubmit"
          >
            确认
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.check {
  padding: 0 20px;

  &-upload {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  &-header {
    color: #ff7e00;
  }

  &-active {
    background-color: #f1f4ff;
    border-color: #6486ff !important;
    color: #4551ff;
  }

  &-icon {
    position: absolute;
    top: -8px;
    right: -6px;
  }

  &-center {
    display: flex;
    flex-wrap: wrap;
    margin: 20px 0;

    &-item {
      position: relative;
      border: 1px solid #bbb;
      display: flex;
      cursor: pointer;
      align-items: center;
      justify-content: center;
      margin: 10px;
      padding: 5px 20px;
    }
  }
}
</style>
